﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Pfz.Factoring;

namespace Pfz.WpfControls.ValueControls
{
	[AutoRegisterInControlFactory(typeof(Color))]
	[AutoRegisterInControlFactory(typeof(Color?))]
	internal sealed class ColorControl:
		UserControl,
		IValueControl
	{
		private ComboBox _comboBox = new ComboBox();
		public ColorControl()
		{
			var items = _comboBox.Items;
			items.Add("");
			foreach(var property in typeof(Colors).GetProperties())
			{
				if (property.CanRead && property.PropertyType == typeof(Color))
				{
					var name = property.Name;
					var color = (Color)property.GetValue(null, null);

					var brush = new Border();
					brush.Background = new SolidColorBrush { Color = color };
					brush.Margin = new Thickness(2);
					brush.Width = 19;
					brush.Height = 19;
					
					var label = new Label();
					label.Content = name;

					var content = new StackPanel();
					content.Orientation = Orientation.Horizontal;

					content.Children.Add(brush);
					content.Children.Add(label);

					ComboBoxItem item = new ComboBoxItem();
					item.Content = content;

					items.Add(item);
				}
			}

			Content = _comboBox;
		}

		public void Clear()
		{
			_comboBox.SelectedItem = null;
		}

		public bool IsReadOnly
		{
			get
			{
				return !_comboBox.IsEnabled;
			}
			set
			{
				_comboBox.IsEnabled = !value;
			}
		}

		public object Value
		{
			get
			{
				var selectedItem = _comboBox.SelectedItem as ComboBoxItem;
				if (selectedItem == null)
					return null;

				var panel = (StackPanel)selectedItem.Content;
				var border = (Border)panel.Children[0];
				var background = (SolidColorBrush)border.Background;
				return background.Color;
			}
			set
			{
				if (value == null)
				{
					_comboBox.SelectedItem = null;
					return;
				}

				var color = (Color)value;
				int index = -1;
				foreach(var item in _comboBox.Items)
				{
					index++;
					var comboItem = item as ComboBoxItem;
					if (comboItem == null)
						continue;

					var panel = (StackPanel)comboItem.Content;
					var border = (Border)panel.Children[0];
					var background = (SolidColorBrush)border.Background;
					if (color == background.Color)
					{
						_comboBox.SelectedIndex = index;
						return;
					}
				}
			}
		}
	}
}
